package EventHandler
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.FileFilter;
	import flash.net.FileReference;
	
	public class XMLSaver
	{
		private var fileRef:FileReference; 
		public function XMLSaver(xmlData:XML,fileName:String):void
		{
			fileRef = new FileReference();
			
			fileRef.addEventListener(Event.SELECT, onFileSelected); 
			fileRef.addEventListener(Event.CANCEL, onCancel); 
			fileRef.addEventListener(IOErrorEvent.IO_ERROR, onIOError); 
			fileRef.addEventListener(Event.COMPLETE, onComplete);
			fileRef.save(xmlData,fileName);
		}
		
		public function onFileSelected(event:Event):void 
		{ 
//			fileRef.addEventListener(ProgressEvent.PROGRESS, onProgress); 
//			fileRef.load(); 
		trace (event)
		} 
		
		public function onProgress(evt:ProgressEvent):void 
		{ 
			trace("Loaded " + evt.bytesLoaded + " of " + evt.bytesTotal + " bytes."); 
		} 
		public function onCancel(evt:Event):void 
		{ 
			trace("The browse request was canceled by the user."); 
		} 
		public function onComplete(evt:Event):void 
		{ 
			trace("File was successfully saved."); 
			fileRef.removeEventListener(Event.SELECT, onFileSelected); 
			fileRef.removeEventListener(ProgressEvent.PROGRESS, onProgress); 
			fileRef.removeEventListener(Event.COMPLETE, onComplete); 
			fileRef.removeEventListener(Event.CANCEL, onCancel); 
		} 
		public function saveFile(xmlData:XML,fileName:String):void 
		{ 
			fileRef.addEventListener(Event.SELECT, onSaveFileSelected); 
			fileRef.save(xmlData,fileName); 
		} 
		
		public function onSaveFileSelected(evt:Event):void 
		{ 
			fileRef.addEventListener(ProgressEvent.PROGRESS, onSaveProgress); 
			fileRef.addEventListener(Event.COMPLETE, onSaveComplete); 
			fileRef.addEventListener(Event.CANCEL, onSaveCancel); 
		} 
		
		public function onSaveProgress(evt:ProgressEvent):void 
		{ 
			trace("Saved " + evt.bytesLoaded + " of " + evt.bytesTotal + " bytes."); 
		} 
		
		public function onSaveComplete(evt:Event):void 
		{ 
			trace("File saved."); 
			fileRef.removeEventListener(Event.SELECT, onSaveFileSelected); 
			fileRef.removeEventListener(ProgressEvent.PROGRESS, onSaveProgress); 
			fileRef.removeEventListener(Event.COMPLETE, onSaveComplete); 
			fileRef.removeEventListener(Event.CANCEL, onSaveCancel); 
		} 
		
		public function onSaveCancel(evt:Event):void 
		{ 
			trace("The save request was canceled by the user."); 
		} 
		
		public function onIOError(evt:IOErrorEvent ):void 
		{ 
			trace("There was an IO Error."); 
		} 
		public function onSecurityError(evt:Event):void 
		{ 
			trace("There was a security error."); 
		} 
	} 
}
